//
//  BKPhotoScrollView.m
//  XPhoto
//
//  Created by baboy on 2019/6/27.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "BKPhotoScrollView.h"
#import "UIImageView+cache.h"
#import "BKPlayerView.h"
#import <AFNetworking/UIImageView+AFNetworking.h>

@interface BKPhotoScrollView()<UIScrollViewDelegate>
@property(nonatomic, strong) NSMutableArray *itemViews;
@end
@implementation BKPhotoScrollView
- (id)init{
    if(self = [super init]){
    }
    return self;
}
- (void)awakeFromNib{
    [super awakeFromNib];
}
- (UIScrollView*)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        _scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        _scrollView.pagingEnabled = YES;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.delegate = self;
        [self addSubview:_scrollView];
        [self bringSubviewToFront:_pageControl];
    }
    return _scrollView;
}
- (UIPageControl*)pageControl{
    if (!_pageControl) {
        CGRect pageControlFrame = CGRectMake(0, self.bounds.size.height-20, self.bounds.size.width, 20);
        _pageControl = [[UIPageControl alloc] initWithFrame:pageControlFrame];
        _pageControl.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleTopMargin;
        [self addSubview:_pageControl];
    }
    return _pageControl;
}
- (BOOL)_scrollLoop{
    BOOL f = self.scrollLoop && self.photos.count>1;
    return f;
}
- (void)layoutScrollView{
    CGRect itemViewFrame = self.scrollView.bounds;
    if (self.itemViews) {
        for (NSInteger i = 0; i<self.itemViews.count; i++) {
            UIView *itemView = [self.itemViews objectAtIndex:i];
            itemViewFrame.origin.x = i * itemViewFrame.size.width;
            itemView.frame = itemViewFrame;
        }
        self.scrollView.contentSize = CGSizeMake(self.itemViews.count*itemViewFrame.size.width, 0);
    }
    if ([self _scrollLoop]) {
        NSInteger i = 1+self.pageControl.currentPage;
        CGPoint contentOffset = CGPointMake(itemViewFrame.size.width * i, 0);
        self.scrollView.contentOffset = contentOffset;
    }
}
- (void)layoutSubviews{
    [super layoutSubviews];
    [self layoutScrollView];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (BKPlayerView *) createPlayerView:(BKPhotoItem *)photoItem withFrame:(CGRect) frame{
    BKPlayerView *view = [BKPlayerView view];
    view.frame = frame;
    if (photoItem.thumb) {
        if ([photoItem.thumb rangeOfString:@"http" options:NSCaseInsensitiveSearch].location != 0) {
            view.coverURL = [NSURL fileURLWithPath:photoItem.thumb];
        }else{
            view.coverURL = [NSURL URLWithString:photoItem.thumb];
        }
    }
    if (photoItem.url) {
        if ([photoItem.url rangeOfString:@"http" options:NSCaseInsensitiveSearch].location != 0) {
            view.videoURL = [NSURL fileURLWithPath:photoItem.url];
        }else{
            view.videoURL = [NSURL URLWithString:photoItem.url];
        }
    }
    return view;
}
- (UIImageView *)createPhotoView:(BKPhotoItem *)photoItem withFrame:(CGRect) frame{
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
//    imageView.backgroundColor = [UIColor redColor];
//    [imageView setImageURLString:photoItem.url placeholderImage:[UIImage imageNamed:@"image"]];
    [imageView setImageWithURL:[NSURL URLWithString:photoItem.url] placeholderImage:nil];
    return imageView;
}
- (void)setPhotos:(NSArray *)photos{
    if (self.itemViews) {
        [self.itemViews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    }
    self.itemViews = [NSMutableArray array];
    _photos = photos;
    CGRect itemViewFrame = self.scrollView.bounds;
    NSInteger itemCount = photos.count;
    if ([self _scrollLoop]) {
        itemCount += 2;
    }
    for (NSInteger i = 0; i < itemCount; i++) {
        NSInteger index = i;
        if ([self _scrollLoop]) {
            index = (i + photos.count-1)%photos.count;
        }
        BKPhotoItem *photoItem = photos[index];
        UIView *itemView = nil;
        if ([BKPHOTO_ITEM_TYPE_VIDEO isEqualToString:photoItem.type]) {
            BKPlayerView *playerView = [self createPlayerView:photoItem withFrame:itemViewFrame];
            itemView = playerView;
        }else{
            itemView = [self createPhotoView:photoItem withFrame:itemViewFrame];
        }
        [self.scrollView addSubview:itemView];
        [self.itemViews addObject:itemView];
        itemViewFrame.origin.x += itemViewFrame.size.width;
    }
    self.pageControl.numberOfPages = photos.count;
    self.pageControl.hidden = photos.count<2;
    self.pageControl.currentPage = 0;
    self.scrollView.contentSize = CGSizeMake(self.itemViews.count*itemViewFrame.size.width, 0);
    [self layoutScrollView];
}
- (void)updateCurrentPageWithContentOffset:(BOOL)updateContentOffset{
    int i = (self.scrollView.contentOffset.x + self.scrollView.bounds.size.width/2)/self.scrollView.bounds.size.width;
    NSInteger currentPage = i;
    if ([self _scrollLoop]) {
        currentPage = (i + self.photos.count-1)%self.photos.count;
        if( i == (self.itemViews.count-1) && updateContentOffset ) {
            self.scrollView.contentOffset = CGPointMake(self.scrollView.bounds.size.width, 0);
        }
        if( i == 0 && updateContentOffset) {
            self.scrollView.contentOffset = CGPointMake(self.photos.count* self.scrollView.bounds.size.width, 0);
        }
    }
    self.pageControl.currentPage = currentPage;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self updateCurrentPageWithContentOffset:NO];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self updateCurrentPageWithContentOffset: YES];
}
- (void)stopPlay{
    if (self.itemViews) {
        for (UIView *v in self.itemViews) {
            if ([v isKindOfClass:[BKPlayerView class]]) {
                [[(BKPlayerView *)v player] pause];
            }
        }
    }
}
@end


@implementation BKPhotoItem
@end
